# -*- coding: utf-8 -*-
import codecs
import os
import zipfile

html_common_header = """<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="provider" content="www.hengha.info"/>
<meta name="builder" content="python"/>
<meta name="right" content="python"/>
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<script src="js/main.js" type="text/javascript"></script>
<title>%s</title>
</head>
<body>
<div>"""

html_cover_page_template = """<div style="text-align:center">
<img class="cover" src="images/cover.jpg"/></div>
<h1>%s</h1><h2>%s</h2><b>简介</b></div></body></html>
"""


def prepare_epub(name, author, slug):
    f = codecs.open(slug + '/epub/mimetype', 'w', 'utf-8')
    f.write('application/epub+zip\n')
    f.close()
    if not os.path.exists(slug + '/epub/META-INF'):
        os.mkdir(slug + '/epub/META-INF')
    f = codecs.open(slug + '/epub/META-INF/container.xml', 'w', 'utf-8')
    tf = codecs.open('ebook/container.xml', 'r', 'utf-8')
    f.write(tf.read())
    tf.close()
    f.close()
    if not os.path.exists(slug + '/epub/OPS'):
        os.mkdir(slug + '/epub/OPS')
    if not os.path.exists(slug + '/epub/OPS/css'):
        os.mkdir(slug + '/epub/OPS/css')
    if not os.path.exists(slug + '/epub/OPS/images'):
        os.mkdir(slug + '/epub/OPS/images')
    f = codecs.open(slug + '/epub/OPS/css/main.css', 'w', 'utf-8')
    tf = codecs.open('ebook/main.css', 'r', 'utf-8')
    f.write(tf.read())
    tf.close()
    f.close()
    names = generate_epub_files()
    generate_epub_cover_image(name, author)
    generate_epub_coverpage(name, author, slug)
    generate_epub_ncx(names)
    generate_epub_opf(names)
    generate_epub()


def parse_to_title_body(content):
    lines = content.splitlines()
    return (lines[0].strip(), ''.join(['<p>' + x + '</p>' for x in lines[1:]]))


def generate_epub_files(slug):
    for root, dirs, files in os.walk(slug + "/txt", topdown=False):
        file_list = sorted(files)
        for name in file_list:
            with open(os.path.join(root, name), 'w') as tf:
                hname = slug + '/epub/OPS' + '/chapter' + \
                    name.replace('.txt', '.html')
                with codecs.open(hname, 'w', 'utf-8') as hf:
                    title, content = parse_to_title_body(tf.read())
                    hf.write(html_common_header % (title,))
                    hf.write(content)
                    hf.write('</div></body></html>')

        return file_list


def generate_epub_cover_image(name, author):
    pass


def generate_epub_coverpage(name, author, slug):
    filename = slug + '/epub/OPS/coverpage.html'
    with codecs.open(filename, 'w', 'utf-8') as hf:
        hf.write(html_common_header % ('bookcover',))
        hf.write(html_cover_page_template % (name, author))
        hf.close()


def generate_epub_ncx(names):
    pass


def generate_epub_opf(names):
    pass


def generate_epub(name, slug):
    archive = zipfile.ZipFile(name + '.epub', "w", zipfile.ZIP_DEFLATED)
    path_name = os.path.join(slug, 'epub')
    for root, dirs, files in os.walk(path_name):
        for file in files:
            print(file, root)
            f = os.path.join(root, file)
            archive.write(f, f.replace(path_name, ''))
    archive.close()
